package org.sn.jdish.example.thread;

public class TestThread {

	public static void main(String[] args) {
		threadTest();
	}

	/**
	 * 打印奇数偶数
	 */
	public static void threadTest() {
		Num num = new Num();

		new Thread(new Runnable() {
			// 打印奇数
			@Override
			public void run() {
				synchronized (num) {
					while (num.i < 100) {
						if (num.flag) {
							try {
								num.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						} else {
							System.out.println("奇数");
							System.out.println(Thread.currentThread().getName() + ": " + num.i++);
							num.flag = true;
							num.notify();
						}
					}
				}
			}
		}).start();

		new Thread(new Runnable() {
			// 打印偶数
			@Override
			public void run() {
				synchronized (num) {
					while (num.i < 100) {
						if (!num.flag) {
							try {
								num.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						} else {
							System.out.println("偶数");
							System.out.println(Thread.currentThread().getName() + ": " + num.i++);
							num.flag = false;
							num.notify();
						}
					}
				}
			}
		}).start();
	}

}
